package edu.uestc.gene.ui.controller;

import java.util.Iterator;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import edu.uestc.gene.model.Statistics;
import edu.uestc.gene.ui.view.ConfigComposite;

public class ConfigCompositeController extends ConfigComposite {

	private DataCompositeController dataCompositeController;
	private Shell shell;
	private Statistics statisticsInstance;

	public ConfigCompositeController(
			DataCompositeController dataCompositeController, Composite parent,
			int style) {
		super(parent, style);
		this.dataCompositeController = dataCompositeController;
		shell = parent.getShell();
		statisticsInstance = Statistics.getInstance();
		// active();
	}

	/**
	 * private void active() { help.addSelectionListener(new SelectionAdapter()
	 * {
	 * 
	 * @Override public void widgetSelected(SelectionEvent e) { new
	 *           HelpShell(shell); } }); dg_button.addSelectionListener(new
	 *           SelectionAdapter() {
	 * @Override public void widgetSelected(SelectionEvent e) { FileDialog fd =
	 *           new FileDialog(shell); fd.setFilterExtensions(new String[] {
	 *           "*.txt" }); String file = fd.open(); if (file == null ||
	 *           file.equals("")) { return; } dg_text.setText(file);
	 *           dg_text.setSelection(file.length()); final List<String> list =
	 *           statisticsInstance.dataInput(file, Statistics.FLAG_D_G); final
	 *           org.eclipse.swt.widgets.List dg = dataCompositeController
	 *           .getDg_list(); dg.removeAll();
	 *           dataCompositeController.setSelection(0);
	 *           Display.getCurrent().asyncExec(new Runnable() { public void
	 *           run() { for (String str : list) { dg.add(str); } } }); } });
	 *           da_button.addSelectionListener(new SelectionAdapter() {
	 * @Override public void widgetSelected(SelectionEvent e) { FileDialog fd =
	 *           new FileDialog(shell); fd.setFilterExtensions(new String[] {
	 *           "*.txt" }); String file = fd.open(); if (file == null ||
	 *           file.equals("")) { return; } da_text.setText(file);
	 *           da_text.setSelection(file.length()); final List<String> list =
	 *           statisticsInstance.dataInput(file, Statistics.FLAG_D_A); final
	 *           org.eclipse.swt.widgets.List da = dataCompositeController
	 *           .getDa_list(); da.removeAll();
	 *           dataCompositeController.setSelection(1);
	 *           Display.getCurrent().asyncExec(new Runnable() { public void
	 *           run() { for (String str : list) { da.add(str); } } }); } });
	 *           index.addSelectionListener(new SelectionAdapter() {
	 * @Override public void widgetSelected(SelectionEvent e) { Cursor cur = new
	 *           Cursor(Display.getCurrent(), SWT.CURSOR_WAIT);
	 *           shell.setCursor(cur); try { statisticsInstance.index(); } catch
	 *           (NullPointerException e1) { ShellUtil.getMessage(shell, "错误",
	 *           "索引文件错误，请重新录入数据文件！", SWT.ICON_ERROR); return; } catch
	 *           (StringIndexOutOfBoundsException e2) {
	 *           ShellUtil.getMessage(shell, "错误", "索引文件错误，请重新录入数据文件！",
	 *           SWT.ICON_ERROR); return; } finally { shell.setCursor(null); cur
	 *           = null; } statistics.setEnabled(true); ShellUtil
	 *           .getMessage(shell, "成功", "成功索引数据文件！", SWT.ICON_WORKING); } });
	 *           gene1_text.addFocusListener(new FocusAdapter() {
	 * @Override public void focusGained(FocusEvent e) { if
	 *           (gene1_text.getText().equals("输入第一个基因"))
	 *           gene1_text.setText(""); } }); gene2_text.addFocusListener(new
	 *           FocusAdapter() {
	 * @Override public void focusGained(FocusEvent e) { if
	 *           (gene2_text.getText().equals("输入第二个基因"))
	 *           gene2_text.setText(""); } });
	 *           statistics.addSelectionListener(new SelectionAdapter() {
	 * @Override public void widgetSelected(SelectionEvent e) { Map<String,
	 *           String> result; int index = 3; String gene1 =
	 *           gene1_text.getText().trim(); String gene2 =
	 *           gene2_text.getText().trim(); if (gene2.equals("") ||
	 *           gene2.equals("输入第二个基因")) { index = 2; } if (index == 2) {//
	 *           如果是单输入
	 *           dataCompositeController.getSingleResultTable().removeAll(); if
	 *           (!statisticsInstance.checkGene(gene1)) {// 如果输入的基因不存在
	 *           ShellUtil.getMessage(shell, "错误", "输入基因 " + gene1 +
	 *           " 不存在，请检查后重新输入！", SWT.ICON_ERROR); return; } result =
	 *           statisticsInstance.dataHandle(gene1); int size = count(result);
	 *           dataCompositeController.getSingleGene_label() .setText(gene1);
	 *           dataCompositeController.getSingleResult_label().setText( "共 " +
	 *           size + " 种副作用"); Iterator it = result.entrySet().iterator();
	 *           int i = 0; while (it.hasNext()) { i++; Map.Entry entry =
	 *           (Map.Entry) it.next(); TableItem ti = new
	 *           TableItem(dataCompositeController .getSingleResultTable(), 0);
	 *           String[] drugs = entry.getValue().toString().split(",");
	 *           ti.setText(new String[] { i + "",// 序号
	 *           entry.getKey().toString(),// 副作用名称 drugs.length + "",// 药物数量
	 *           Tool.roundDivisionString(drugs.length, size, 10) + "",//
	 *           概率，保留10位小数 entry.getValue().toString() });// 所有药物 } } else {//
	 *           如果是双输入 boolean flag1 = true, flag2 = true; if
	 *           (!statisticsInstance.checkGene(gene1)) {// 如果输入的基因不存在 flag1 =
	 *           false; } if (!statisticsInstance.checkGene(gene2)) { flag2 =
	 *           false; } String errorGene = ""; if (!flag1) errorGene += " " +
	 *           gene1 + " "; if (!flag2) errorGene += " " + gene2 + " "; if
	 *           (!flag1 || !flag2) { ShellUtil.getMessage(shell, "错误", "输入基因" +
	 *           errorGene + "不存在，请检查后重新输入！", SWT.ICON_ERROR); return; }
	 *           dataCompositeController.getDoubleResultTable().removeAll();
	 *           result = statisticsInstance.dataHandle(gene1, gene2); int size
	 *           = count(result);
	 *           dataCompositeController.getDoubleGene_label().setText( gene1 +
	 *           " , " + gene2); Iterator it = result.entrySet().iterator(); int
	 *           i = 0; while (it.hasNext()) { i++; Map.Entry entry =
	 *           (Map.Entry) it.next(); TableItem ti = new
	 *           TableItem(dataCompositeController .getDoubleResultTable(), 0);
	 *           String[] drugs = entry.getValue().toString().split(",");
	 *           ti.setText(new String[] { i + "",// 序号
	 *           entry.getKey().toString(),// 副作用名称 drugs.length + "",// 药物数量
	 *           Tool.roundDivisionString(drugs.length, size, 10) + "",//
	 *           概率，保留10位小数 entry.getValue().toString() });// 所有药物 } }
	 *           dataCompositeController.setSelection(index);// 跳转到相应的标签页 } });
	 *           Table singleResultTable, doubleResultTable;// 给两个统计结果表格添加排序器
	 *           singleResultTable =
	 *           dataCompositeController.getSingleResultTable();
	 *           doubleResultTable =
	 *           dataCompositeController.getDoubleResultTable();
	 *           addNumberSorter(singleResultTable,
	 *           singleResultTable.getColumn(0));
	 *           addNumberSorter(singleResultTable,
	 *           singleResultTable.getColumn(2));
	 *           addNumberSorter(singleResultTable,
	 *           singleResultTable.getColumn(3));
	 *           addNumberSorter(doubleResultTable,
	 *           doubleResultTable.getColumn(0));
	 *           addNumberSorter(doubleResultTable,
	 *           doubleResultTable.getColumn(2));
	 *           addNumberSorter(doubleResultTable,
	 *           doubleResultTable.getColumn(3)); }
	 */

	/**
	 * 给表格的指定列添加数值排序器，使用Collator类比较两个float类型数值的大小
	 * 
	 * @param table
	 *            记录数据的表对象
	 * @param column
	 *            表中的某数值列
	 */
	private void addNumberSorter(final Table table, final TableColumn column) {
		column.addListener(SWT.Selection, new Listener() {
			boolean isAscend = true; // 按照升序排序

			public void handleEvent(Event e) {
				int columnIndex = getColumnIndex(table, column);
				TableItem[] items = table.getItems();
				// 使用冒泡法进行排序
				for (int i = 1; i < items.length; i++) {
					String strvalue2 = items[i].getText(columnIndex);
					if (strvalue2.equalsIgnoreCase("")) {
						// 当遇到表格中的空项目时，就停止往下检索排序项目
						break;
					}
					for (int j = 0; j < i; j++) {
						String strvalue1 = items[j].getText(columnIndex);
						// 将字符串类型数据转化为float类型
						float numbervalue1 = Float.valueOf(strvalue1);
						float numbervalue2 = Float.valueOf(strvalue2);
						boolean isLessThan = false;
						if (numbervalue2 < numbervalue1) {
							isLessThan = true;
						}
						if ((isAscend && isLessThan)
								|| (!isAscend && !isLessThan)) {
							String[] values = getTableItemText(table, items[i]);
							Object obj = items[i].getData();
							items[i].dispose();
							TableItem item = new TableItem(table, SWT.NONE, j);
							item.setText(values);
							item.setData(obj);
							items = table.getItems();
							break;
						}
					}
				}
				table.setSortColumn(column);
				table.setSortDirection((isAscend ? SWT.UP : SWT.DOWN));
				isAscend = !isAscend;
			}
		});

	}

	/**
	 * 获取某列对应的索引号
	 * 
	 * @param table
	 *            记录数据的表对象
	 * @param column
	 *            表中的某列
	 */
	private int getColumnIndex(Table table, TableColumn column) {
		TableColumn[] columns = table.getColumns();
		for (int i = 0; i < columns.length; i++) {
			if (columns[i].equals(column))
				return i;
		}
		return -1;
	}

	/**
	 * 获取某列对应的文本
	 * 
	 * @param table
	 *            记录数据的表对象
	 * @param column
	 *            表中的某列
	 */
	private String[] getTableItemText(Table table, TableItem item) {
		int count = table.getColumnCount();
		String[] strs = new String[count];
		for (int i = 0; i < count; i++) {
			strs[i] = item.getText(i);
		}
		return strs;
	}

	private int count(Map<String, String> result) {
		Iterator it = result.entrySet().iterator();
		int i = 0;
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			i += entry.getValue().toString().split(",").length;
		}
		return i;
	}
}
